package com.manage.modules.utils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期处理类
 *
 * @author xu
 * 2021/8/18 15:38
 */
public class DateUtil {
    public static String YYYYMMDDHH = "yyyyMMddHH";
    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";


    /**
     * 获取当前时间的String类型
     * 格式为：2021081810
     */
    public static String getNowDate() {
        LocalDateTime now = LocalDateTime.now();
        return getDate(YYYYMMDDHH, now);
    }

    public static String getNowDateTime() {
        LocalDateTime now = LocalDateTime.now();
        return getDate(YYYYMMDDHHMMSS, now);
    }

    /**
     * localDate 转 date
     *
     * @param localDateTime
     * @return
     */
    public static Date localToDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取时间的string类型转换
     *
     * @param pattern       转换格式
     * @param localDateTime 时间
     */
    public static String getDate(String pattern, LocalDateTime localDateTime) {
        // 转换格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return localDateTime.format(formatter);
    }

    /**
     * 将date 转为 localDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime dateTimeToLocal(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * 时间比较 startTime 是否在endTime 时间之前
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean isBefore(LocalDateTime startTime, LocalDateTime endTime) {
        return startTime.isBefore(endTime);
    }

    /**
     * 时间相差小时数 负数代表前面一个时间在后面一个时间之后
     *
     * @return
     */
    public static Long betweenHours(LocalDateTime startTime, LocalDateTime endTime) {
        Duration duration = Duration.between(startTime, endTime);
        return duration.toHours();
    }

    /**
     * 时间相差分钟数 负数代表前面一个时间在后面一个时间之后
     *
     * @return
     */
    public static Long betweenMinutes(LocalDateTime startTime, LocalDateTime endTime) {
        Duration duration = Duration.between(startTime, endTime);
        return duration.toMinutes();
    }

    public static void main(String[] args) {
        LocalDateTime endTime = LocalDateTime.of(2021, 9, 8, 16, 45, 33);
        System.out.println(betweenMinutes(LocalDateTime.now(), endTime));
    }
}
